import pytest
from py.xml import html

from pytest_html import extras


def pytest_html_report_title(report):
    """
    自定义pytest-html报告标题
    :param report:
    :return:
    """
    report.title = "My very own title!"


def pytest_html_results_summary(prefix, summary, postfix):
    """
    向生成的html报告summary中添加自定义内容
    :param prefix:
    :param summary:
    :param postfix:
    :return: None
    """
    prefix.extend([html.p("测试者: 八哥")])
    # prefix.extend([html.p("测试时间: 2022/04/29")])


def pytest_configure(config):
    config._metadata["foo"] = "bar"


@pytest.hookimpl(tryfirst=True)
def pytest_sessionfinish(session, exitstatus):
    session.config._metadata["foo"] = "bar2"


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    pytest_html = item.config.pluginmanager.getplugin("html")
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, "extra", [])
    if report.when == "call":
        # always add url to report
        extra.append(pytest_html.extras.url("http://www.example.com/"))
        extra.append(pytest_html.extras.text("这是一份测试报告", name="Different title"))
        extra.append(pytest_html.extras.html("<div>Additional HTML</div>"))
        # extra.append(pytest_html.extras.image("https://img2.baidu.com/it/u=1572613686,938558453&fm=253&fmt=auto&app=120&f=JPEG?w=640&h=400"))
        html = '<div><img src="https://img2.baidu.com/it/u=1572613686,938558453&fm=253&fmt=auto&app=120&f=JPEG?w=640&h=400" alt="screenshot" style="width:304px;height:228px;" ' \
               'onclick="window.open(this.src)" align="right"/></div>'
        extra.append(pytest_html.extras.html(html))
        # xfail = hasattr(report, "wasxfail")
        # if (report.skipped and xfail) or (report.failed and not xfail):
        #     # pass
        #     # only add additional html on failure
        #     extra.append(pytest_html.extras.html("<div>Additional HTML</div>"))
        report.extra = extra
